import { useRef } from 'react';

type DependencyList = any[];

// 本质还是useref，但加上了一个模拟deps并每次重渲染的时候diff更新ref
export function useCreation<T>(factory: () => T, deps: DependencyList) {
  const { current } = useRef<{ deps: any[]; obj: T | undefined; initialized: boolean }>({
    deps: [],
    obj: undefined,
    initialized: false,
  });
  // 判断是否更新ref
  if (current.initialized === false || !depsAreSame(current.deps, deps)) {
    current.deps = deps;
    current.obj = factory();
    current.initialized = true;
  }
  return current.obj as T;
}

// 深比较(值相等，并且指向堆中的同一块内存空间)
function depsAreSame(oldDeps: DependencyList, deps: DependencyList): boolean {
  // console.log('depsAreSame--oldDeps, deps--', oldDeps, deps, oldDeps === deps);
  if (oldDeps === deps) return true; // 引用地址相同，则认为deps没有变化  useCreation(() => {},[])  []时 肯定是false
  for (let i = 0; i < oldDeps.length; i++) {
    if (!Object.is(oldDeps[i], deps[i])) return false;
  }
  return true;
}